/**
 * Copyright 2009 Sergio Bossa
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.googlecode.actorom.impl.core;

import com.googlecode.actorom.ThreadingPolicy;
import com.googlecode.actorom.FailoverPolicy;
import com.googlecode.actorom.impl.core.reactor.MessageDispatcher;
import com.googlecode.actorom.impl.core.reactor.MessageQueue;
import com.googlecode.actorom.Actor;
import com.googlecode.actorom.Address;
import com.googlecode.actorom.CompletableFutureResult;
import com.googlecode.actorom.ExitReason;
import com.googlecode.actorom.Topology;
import com.googlecode.actorom.impl.core.failover.FailoverAction;
import com.googlecode.actorom.impl.core.failover.FailoverScheme;
import com.googlecode.actorom.impl.core.failover.FailoverSchemeFactory;
import com.googlecode.actorom.impl.core.reactor.MessageDemultiplexer;
import com.googlecode.actorom.impl.core.reactor.MessageHandle;
import com.googlecode.actorom.impl.core.reactor.MessageHandler;
import com.googlecode.actorom.support.ActorCreationException;
import com.googlecode.actorom.support.TopologyException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import net.jcip.annotations.ThreadSafe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Sergio Bossa
 */
@ThreadSafe
public abstract class AbstractTopology implements Topology {

    private static final transient Logger LOG = LoggerFactory.getLogger(AbstractTopology.class);
    private final Map<Address, CoreActor> actors = new HashMap<Address, CoreActor>();
    private final MessageDispatcher messageDispatcher;
    private final MessageDemultiplexer messageDemultiplexer;
    private final MessageQueue messageQueue;
    private final FailoverSchemeFactory failoverSchemeFactory;
    private volatile boolean shutdown;

    public AbstractTopology(ThreadingPolicy threadingPolicy, FailoverPolicy failoverPolicy) {
        messageDispatcher = threadingPolicy.getMessageDispatcher();
        messageDemultiplexer = threadingPolicy.getMessageDemultiplexer();
        messageQueue = threadingPolicy.getMessageQueue();
        failoverSchemeFactory = failoverPolicy.getFailoverSchemeFactory();
        messageDispatcher.dispatch(messageDemultiplexer, messageQueue);
    }

    protected final synchronized boolean doSpawnActor(Address address, Object handler) {
        if (!shutdown) {
            if (!actors.containsKey(address)) {
                LOG.info("Spawning actor with address: {}", address);
                CoreActor actor = new CoreActor(this, address, handler, messageQueue, new ActorExitListener());
                boolean spawned = actor.spawn();
                if (spawned) {
                    actors.put(address, actor);
                    messageDispatcher.registerHandler(address, new ActorMessageHandler(actor));
                    return true;
                } else {
                    return false;
                }
            } else {
                throw new ActorCreationException("Address already assigned to another actor: " + address);
            }
        } else {
            throw new TopologyException("Topology is shutdown!");
        }
    }

    protected final synchronized Actor doGetActor(Address address) {
        if (!shutdown) {
            CoreActor actor = actors.get(address);
            if (actor != null && actor.isActive()) {
                return actor;
            } else {
                return null;
            }
        } else {
            throw new TopologyException("Topology is shutdown!");
        }
    }

    protected final synchronized void doShutdown() {
        shutdown = true;
        messageDispatcher.shutdown();
    }

    private synchronized void reactOnKill(CoreActor killed) {
        FailoverScheme scheme = failoverSchemeFactory.makeFailoverScheme(killed.getAddress());
        Set<Address> addresses = new HashSet<Address>(actors.keySet());
        for (Address address : addresses) {
            if (scheme.getFailoverActionFor(address).equals(FailoverAction.RESTART)) {
                restartActor(actors.get(address), ExitReason.KILL);
            } else if (scheme.getFailoverActionFor(address).equals(FailoverAction.EXIT)) {
                exitActor(actors.get(address), ExitReason.KILL);
            }
        }
    }

    private synchronized void reactOnFail(CoreActor failed) {
        FailoverScheme scheme = failoverSchemeFactory.makeFailoverScheme(failed.getAddress());
        Set<Address> addresses = new HashSet<Address>(actors.keySet());
        for (Address address : addresses) {
            if (scheme.getFailoverActionFor(address).equals(FailoverAction.RESTART)) {
                restartActor(actors.get(address), ExitReason.FAIL);
            } else if (scheme.getFailoverActionFor(address).equals(FailoverAction.EXIT)) {
                exitActor(actors.get(address), ExitReason.FAIL);
            }
        }
    }

    private synchronized void restartActor(CoreActor actor, ExitReason reason) {
        boolean restarted = actor.restart(reason);
        if (!restarted) {
            exitActor(actor, reason);
        }
    }

    private synchronized void exitActor(CoreActor actor, ExitReason reason) {
        try {
            actor.exit(reason);
        } finally {
            actors.remove(actor.getAddress());
            messageDispatcher.unregisterHandler(actor.getAddress());
        }
    }

    private class ActorMessageHandler implements MessageHandler {

        private final CoreActor actor;

        public ActorMessageHandler(CoreActor actor) {
            this.actor = actor;
        }

        public void handle(MessageHandle handle) {
            Object message = handle.getMessage();
            CompletableFutureResult future = handle.getFuture();
            actor.handle(message, future);
        }
    }

    private class ActorExitListener implements ExitListener {

        public void onKill(CoreActor killed) {
            AbstractTopology.this.reactOnKill(killed);
        }

        public void onFail(CoreActor failed) {
            AbstractTopology.this.reactOnFail(failed);
        }
    }
}
